<template>
  <div class="attr-list">
    <CommonAttr />
    <px-form>
      <px-form-item label="还原组组件">
        <px-select v-model="compSelected" value-key="id" filterable placeholder="Select" multiple collapse-tags collapse-tags-tooltip>
          <px-option
            v-for="(item, index) in curComponent.propValue.components"
            :key="index"
            :label="dealName(getComponent(index))"
            :value="getComponent(index)"
          />
        </px-select>
        <px-button @click="delComps">确定修改</px-button>
      </px-form-item>
      <px-form-item label="添加组件">
        <px-select v-model="compSelectedAdd" filterable value-key="id" placeholder="Select" multiple collapse-tags collapse-tags-tooltip>
          <px-option
            v-for="(item, index) in filterData"
            :key="index"
            :label="dealName(getComponent(index, filterData))"
            :value="getComponent(index, filterData)"
          />
        </px-select>
        <px-button @click="addComps">确定修改</px-button>
      </px-form-item>
    </px-form>
  </div>
</template>

<script setup lang="ts">
import CommonAttr from "@visual/custom-component/common/CommonAttr.vue";
import { useComponent, useCompose } from "@visual/stores";
import { storeToRefs } from "pinia";
import { computed, inject, onMounted, ref, watch } from "vue";
const { decomposediff, compose, setAreaData } = useCompose();

const componentStore = useComponent();
const { curComponent, componentData } = storeToRefs(componentStore);
import { cloneDeep } from "@pureadmin/utils";
import { eventBus, $, getComponentRotatedStyle } from "@visual/utils";
const flattenTreeData = inject("curTreeData", ref({}));
let pointStr = "DrillLocation TextLocation ColorLocation RectLocation VLocation DrillLocation2 MessageLocation VText middleTip";

const compSelected = ref([]);
const compSelectedAdd = ref([]);
const filterData = computed(() => {
  return componentData.value.filter(item => pointStr.indexOf(item.component) !== -1);
});
watch(
  () => curComponent.value.id,
  id => {
    if (id) {
      compSelected.value = [...curComponent.value.propValue.components];
    }
  },
  { immediate: true }
);

function delComps() {
  let diffs = diffArrays(curComponent.value.propValue.components, compSelected.value, "id");
  console.error(diffs);
  decomposediff(diffs, curComponent);
  curComponent.value.propValue.components = cloneDeep(compSelected.value);
}
function addComps() {
  compSelectedChange();
}
function getComponent(index, target?) {
  if (target) {
    return target[target.length - 1 - index];
  }
  return curComponent.value.propValue.components[curComponent.value.propValue.components.length - 1 - index];
}
function dealName(comp) {
  if (pointStr.indexOf(comp.component) === -1) return comp.label ? comp.label : comp.component;
  if (flattenTreeData.value && comp.propValue.routerKey) {
    const curTreeData = flattenTreeData.value[comp.propValue.routerKey];
    if (curTreeData) {
      const { type, code, className: name } = curTreeData;
      if (type === "EQP") {
        return replaceCharWithNewLine(comp.propValue.groupName) || code;
      }
    }
  }
  if (comp.propValue.type === "EQP") {
    return replaceCharWithNewLine(comp.propValue.groupName || comp.propValue.routerKey || comp.propValue.tip);
  } else {
    return replaceCharWithNewLine(comp.propValue.groupName || comp.propValue.tip || comp.label || comp.component);
  }
}

/**
 * 对比两个数组，返回target中不存在的值组成的新数组
 * @param {Array} source 源数组
 * @param {Array} target 目标数组
 * @param {String} key 对比的属性键名
 * @returns {Array} target中不存在的值组成的新数组
 */
function diffArrays(source, target, key) {
  return source.filter(sourceItem => !target.some(targetItem => targetItem[key] === sourceItem[key]));
}
function compSelectedChange() {
  const areaData = [curComponent.value, ...compSelectedAdd.value];

  let top = Infinity,
    left = Infinity;
  let right = -Infinity,
    bottom = -Infinity;
  areaData.forEach(component => {
    let style = {
      left: 0,
      top: 0,
      right: 0,
      bottom: 0
    };
    style = getComponentRotatedStyle(component.style);

    if (style.left < left) left = style.left;
    if (style.top < top) top = style.top;
    if (style.right > right) right = style.right;
    if (style.bottom > bottom) bottom = style.bottom;
  });
  setAreaData({
    style: {
      left,
      top,
      width: right - left,
      height: bottom - top
    },
    label: curComponent.value.label,
    components: areaData
  });
  let groupAttr = cloneDeep(curComponent.value);
  delete groupAttr.propValue;
  delete groupAttr.id;
  Object.assign(groupAttr.style, {
    left,
    top,
    width: right - left,
    height: bottom - top
  });
  compose(componentData, groupAttr);
}
function sortByOrderInA1(a1, a2) {
  // 创建一个映射，存储a1中元素的id和其索引的对应关系
  const idToIndexMap = new Map();
  a1.forEach((item, index) => {
    idToIndexMap.set(item.id, index);
  });

  // 使用map中的索引对a2进行排序
  return a2.sort((a, b) => {
    return idToIndexMap.get(a.id) - idToIndexMap.get(b.id);
  });
}
function replaceCharWithNewLine(str, charToReplace = ",") {
  if (!str) return str;
  try {
    return str.replace(new RegExp(charToReplace, "g"), "\n");
  } catch (e) {
    return str;
  }
}
</script>
